import java.util.*;

public class test1 {
    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> list = new ArrayList<>();
        Arrays.sort(nums);
        int left = 0;
        int ret = nums.length - 1;
        while (nums[ret] >= 0 && ret > 1) {
            int right = ret - 1;
            left = 0;
            while (left < right) {

                if (nums[left] + nums[ret] + nums[right] > 0) {
                    right--;
                }
                else if (nums[left] + nums[ret] + nums[right] < 0) {
                    left++;
                }
                else {
                    list.add(new ArrayList<>(Arrays.asList(nums[left],nums[ret],nums[right])));
                    left++;
                    right--;
                    while (left<right&&nums[left-1]==nums[left])left++;
                    while (left<right&&nums[right+1]==nums[right])right--;
                }

            }
            ret--;
            while (nums[ret] >= 0 && ret > 1&&nums[ret+1]==nums[ret])ret--;
        }
        return list;
    }
}
